// ==UserScript==
// @name              Falcon Combat Commands
// @description       Keyboard commands for PvP combat
// @namespace         falcons.marknas.com
// @author         Carolus Rex, 2011 - updated and adapted from Luschn, Rhindon and Dwarf Prawn versions
// @include           http://*.pardus.at/main.php*
// @include           http://*.pardus.at/building.php*
// @include           http://*.pardus.at/ship2ship_combat.php*
// @version            1.2.0

///////////////////////////////////////////////////////////////
// DEFAULT SETTINGS AND FUNCTIONALITIES (edit from line 140ff):
// ===========================================================
// 1 = Enter combat with the first pilot on screen, faction filtered
// 2 = Attack pilot for 20 rounds
// 3 = Nav (refresh or return to)
// 4 = Jump to the JUMPPOINT tile (set by 0)
// 5 = Use bots, the amount needed, or what's on board if that's not enough
// 9 = Exit inner SB
// 0 = Set current tile to JUMPPOINT (to be used by 4)
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// GLOBAL USER PREFERENCES - edit with caution
// ===========================================
///////////////////////////////////////////////////////////////
// MY ENEMIES
// ==========
//
// myEnemies holds info on pilots that should be attacked, no
// matter what faction they belong to. One set per universe.
// Make sure each pilot object is separated by commas ","  AND
// that you follow the template. This is JSON data, and MUST be
// properly formatted for the attack function to work.
//
// Suppose you will only use the script's attack ability in Orion,
// then your myEnemies variable should look something like this:
// var myEnemies =
// {"orion": {
//      "170192": {"name": "Zerok", "pid": "170192"},
//      "171705": {"name": "Hired Gun", "pid": "171705"},
// },
// "artemis": {},
// "pegasus": {}
// };
///////////////////////////////////////////////////////////////
var myEnemies =
   {"orion": {
        "170192": {"name": "Zerok", "pid": "170192"},
        "171705": {"name": "Hired Gun", "pid": "171705"},
      "24876": {"name": "Firkin Tall", "pid": "24876"},
      "89339": {"name": "Zopa", "pid": "89339"},
      "56153": {"name": "Westwood", "pid": "56153"},
      "55878": {"name": "Quetz", "pid": "55878"},
      "19297": {"name": "Erius", "pid": "19297"},
      "61585": {"name": "Dagobert", "pid": "61585"},
      "29910": {"name": "Q Roger", "pid": "29910"},
      "100532": {"name": "Rubber", "pid": "100532"},
      "31483": {"name": "Armando Salamango", "pid": "31483"},
      "43508": {"name": "Badger", "pid": "43508"},
      "4543": {"name": "Brecht", "pid": "4543"},
      "9031": {"name": "Imhotep", "pid": "9031"},
      "49721": {"name": "Pok", "pid": "49721"},
      "108654": {"name": "Poko Loko", "pid": "108654"},
      "182161": {"name": "Sal al Adin", "pid": "182161"},
      "87219": {"name": "Synergy", "pid": "87219"},
      "165432": {"name": "Verklinkn", "pid": "165432"},
      "29527": {"name": "Georgum", "pid": "29527"},
      "159362": {"name": "Leon Dk", "pid": "159362"},
      "137018": {"name": "Ligting", "pid": "137018"},
      "218496": {"name": "Mr Donutz", "pid": "218496"},
      "15950": {"name": "Neotrunks", "pid": "15950"},
      "187604": {"name": "Rauko Taur Ohtar", "pid": "187604"},
      "221466": {"name": "Redship Rory", "pid": "221466"},
      "220040": {"name": "Usufructo", "pid": "220040"},
      "21490": {"name": "Captain Miller", "pid": "21490"},
      "152806": {"name": "Firedesire", "pid": "152806"},
      "160776": {"name": "Gailurd Fokker", "pid": "160776"},
      "38186": {"name": "Gehenna", "pid": "38186"},
      "190142": {"name": "Hope Hubris", "pid": "190142"},
      "12398": {"name": "Judsea", "pid": "12398"},
      "30440": {"name": "Stryfe", "pid": "30440"},
      "102897": {"name": "Sunni Tzui", "pid": "102897"},
      "45217": {"name": "Tacoman", "pid": "45217"},
      "31274": {"name": "Westerndave", "pid": "31274"},
      "27601": {"name": "Zanoni", "pid": "27601"},
      "177281": {"name": "Jack Crossbones", "pid": "177281"},
      "10891": {"name": "Bobo", "pid": "10891"},
      "25185": {"name": "Crazy Matty H", "pid": "25185"}
    },
   "artemis": {
      "36690": {"name": "Bane", "pid": "36690"}
   },
   "pegasus": {
      "2568": {"name": "William Kidd", "pid": "2568"}
   }
};
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// MY ALLIES
// =========
//
// myAllies holds information about pilots the script will never attack,
// regardless of whether they are in any of your target factios.
// It works like the myEnemies variable, but reversed. Pilots here
// will never be attacked by the script.
//
// Make sure each pilot object is separated by commas ","  AND
// that you follow the template. This is JSON data, and MUST be
// properly formatted for the attack function to work.
//
// Suppose you will only use the script's attack ability in Orion,
// then your myAllies variable should look something like this:
// var myAllies =
// {"orion": {
//      "37864": {"name": "Slam Ruler", "pid": "37864"},
//      "19816": {"name": "Zac Rogers", "pid": "19816"}
// },
// "artemis": {},
// "pegasus": {}
// };
///////////////////////////////////////////////////////////////
var myAllies =
   {"orion": {
      "37864": {"name": "Slam Ruler", "pid": "37864"},
      "19816": {"name": "Zac Rogers", "pid": "19816"}
   },
   "artemis": {
      "123065": {"name": "Rastus", "pid": "123065"}
   },
   "pegasus": {
      "5092": {"name": "Fabius Maximus", "pid": "5092"}
   }
};

///////////////////////////////////////////////////////////////
// MY ARMOUR INFO
// ==============
//
// myArmourInfo holds your various armours, for all three
// universes. Use like this:
// After "ap" for each universe, enter your armour points.
// After "ac" for each universe, enter your armour class.
//
// For armour class, use one of these values: 30 36 45 60  120 180 
// eg 30 for x6 or 180 for x1 armor class.
///////////////////////////////////////////////////////////////
var myArmorInfo = {
   "orion": {"ap": "720", "ac": "36"},
   "artemis": {"ap": "405", "ac": "36"},
   "pegasus": {"ap": "525", "ac": "36"}
};
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// TARGET FACTIONS
// ===============
//
// Who to target? targetFactions is JSON data, feel free
// to edit as you please. Factions are separated by "|",
// one object per universe.
// If you want to target any pilot in Orion, your targetFactions
// should look something like this:
//
// var targetFactions = {
//      "orion": {"targetFactions": "uni|emp|neutral"},
//       "artemis": {},
//       "pegasus": {}
// }
//
///////////////////////////////////////////////////////////////
//var targetFactions = /fed|uni|emp|neutral/i;
var targetFactions = {
   "orion": {"targetFactions": "emp|neutral"},
   "artemis": {"targetFactions": "fed|emp|neutral"},
   "pegasus": {"targetFactions": "fed|uni|neutral"}
};
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// UNIVERSE
// ========
//
// universe is a global variable for storing the universe we're in,
// calculated by the code. DO NOT edit this!
///////////////////////////////////////////////////////////////
var universe = top.window.frames[1].document.getElementById('universe').getAttribute('title');
universe = universe.substring(0, universe.indexOf(":")).toLowerCase();
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// TARGETS
// =======
//
// Derived from the targetFactions and universe variable, this
// variable is used to check if a potential target is to be attacked.
//
// DO NOT EDIT
///////////////////////////////////////////////////////////////
var targets = new RegExp(targetFactions[universe].targetFactions, "i")

///////////////////////////////////////////////////////////////
// ACTIONS
// =======
//
// These are the actions controlled by the script. Do NOT edit
// unless you're 100% sure you know what you are doing.
///////////////////////////////////////////////////////////////
var TARGET       = "js:fightFirst()";
var KILL       = "js:clickButton('button5')";
var NAV       = "main.php";
var JUMP       = "js:jumpToTile()";
var BOT       = "js:consumeBots()";
var EXITSB       = "js:exitInner()";
var JUMPPOINT    = "js:setJumpPoint()";
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// These are the key bindings. Do NOT edit unless you are 100%
// sure you know what you are doing.
///////////////////////////////////////////////////////////////
var KEY_1 = TARGET;
var KEY_2 = KILL;
var KEY_3 = NAV;
var KEY_4 = JUMP;
var KEY_5 = BOT;
var KEY_9 = EXITSB;
var KEY_0 = JUMPPOINT;
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// This is the listener, responsible for detecting and acting
// on the keypresses you do. NO EDITING!
///////////////////////////////////////////////////////////////
window.addEventListener("keypress",doKeyboardAction,true);
///////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////
// The doKeyboardAction function is the function that does the
// trick. This is where you can alter the default keys for the
// various actions.
// Say, for example, you want to map "q" to the target action.
// Find the line below corresponding to KEY_1, and change it to
//
// if (char == 'q') { targetLocation = KEY_1; }
//
///////////////////////////////////////////////////////////////
function doKeyboardAction(e) {
   if(window.name == "") return;

   var keynum = e.which;
   var targetLocation = "";

   var caller = e.target;

   char = String.fromCharCode(keynum).toLowerCase();

   if (char == "1") { targetLocation = KEY_1; }
   else if (char == "2") { targetLocation = KEY_2; }
   else if (char == "3") { targetLocation = KEY_3; }
   else if (char == "4") { targetLocation = KEY_4; }
   else if (char == "5") { targetLocation = KEY_5; }
   else if (char == "9") { targetLocation = KEY_9; }
   else if (char == "0") { targetLocation = KEY_0; }

   if(targetLocation){
      if(targetLocation.substr(0, 3) == "js:"){
         eval(targetLocation);
      }
      else{
         document.location = targetLocation;
      }
   }
}

// Set the combat rounds drop-down to 20, just in case...
if (document.location.href.match("combat.php")){
   document.getElementsByName("rounds")[0].selectedIndex = 19;
}

///////////////////////////////////////////////////////////////
// MAIN SCRIPT FUNCTIONS
// =====================
//
// Below, you will find the main functions of the script. These
// constitute the engine of the script. Do not edit unless you're
// 100% sure what you're doing.
///////////////////////////////////////////////////////////////

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function clickButton(label) {
   // First test is to find it using the label as  the element Id:
   var btn = document.getElementById(label);
   if(btn) {
      btn.click();
      return true;
   }

   // No luck. Second test is to find the label as the button name:
   btn = document.getElementsByName(label);
   if(btn[0]) {
      btn[0].click();
      return true;
   }

   // Still no luck. Perhaps it's an input element:
   inputs = document.getElementsByTagName("input");
   for(var i = 0; i < inputs.length; i++) {
      if(inputs[i].value == label && inputs[i].type == "submit") {
         inputs[i].click();
         return true;
      }
   }

   //Nope, an input button was not found... Try 'button' tags
   buttons = document.getElementsByTagName("button");
   for(var i = 0; i < buttons.length; i++) {
      if(buttons[i].innerHTML == label) {
         buttons[i].click();
         return true;
      }
   }
   
   // Still no input buttons found, the user must be non-premium.
   // Let's try the standard drop-down/attack button instead:
   if (document.location.href.match("combat.php")){
      document.getElementsByName("rounds")[0].selectedIndex = 19;
      document.getElementsByName("ok")[0].click();
      return true;
   }
}

function fightFirst(){
   // Fighting is NOT on a building:
   if(document.location.href.match("main.php")){
      for(var i = 0; i < document.links.length; i++){
         var a = document.links[i];
         if(a.getAttribute("href").search(/main.php[?]scan_details/i) != -1 && a.innerHTML.indexOf('class="nf"') == -1 && a.innerHTML.indexOf("class='nf'") == -1){
            var Thefaction = "";
            var Leparent = a.parentNode;
            var Sonvoisin = Leparent.previousSibling;
            if(Sonvoisin.innerHTML != ''){
               var Sonfils = Sonvoisin.firstChild;
               var sonnom = Sonfils.nodeName.toLowerCase();
               if(sonnom == "img" && sonnom != "br"){
                  Thefaction = Sonfils.src;
               }
            }else{
               Thefaction = "neutral";
            }
            if(Thefaction.trim() == ""){
               Thefaction = "neutral";
            }
                var Someone = a.getAttribute("href").replace("main.php?scan_details=", "").replace("&scan_type=player", "");
            //Check if the target is in myAllies:
            if(!myAllies[universe][Someone]){
               if(Thefaction){
                  if(targets.test(Thefaction)){
                     document.location = a.getAttribute("href").replace("main.php?scan_details=", "ship2ship_combat.php?playerid=").replace("&scan_type=player", "");
                     break;
                  }
                  else if(myEnemies[universe][Someone]){
                     document.location = a.getAttribute("href").replace("main.php?scan_details=", "ship2ship_combat.php?playerid=").replace("&scan_type=player", "");
                     break;
                  }
                  else{
                     // Nothing
                  }
               }
            }
         }
      }
   }else if (document.location.href.match("building.php")){
      // Fighting IS on a building
      for(var i = 0; i < document.links.length; i++){
         var a = document.links[i];
         if(a.getAttribute("href").search(/building.php[?]detail_type=player/i) != -1 && a.innerHTML.indexOf('class="nf"') == -1 && a.innerHTML.indexOf("class='nf'") == -1){
            var Thefaction = "";
            var Leparent = a.parentNode;
            var Sonvoisin = Leparent.previousSibling;
            if(Sonvoisin.innerHTML != ''){
               var Sonfils = Sonvoisin.firstChild;
               var sonnom = Sonfils.nodeName.toLowerCase();
               if(sonnom == "img" && sonnom != "br"){
                  Thefaction = Sonfils.src;
               }
            }
            if (Thefaction == ""){
               Thefaction = "neutral";
            }
            var Someone = a.getAttribute("href").replace("building.php?detail_type=player&detail_id=", "");
            //Check if the target is in myAllies:
            if(!myAllies[universe][Someone]){
               if(targets.test(Thefaction)){
                  document.location = a.getAttribute("href").replace("building.php?detail_type=player&detail_id=", "ship2ship_combat.php?playerid=");
                  break;
               }
               else if(myEnemies[universe][Someone]){
                  document.location = a.getAttribute("href").replace("main.php?scan_details=", "ship2ship_combat.php?playerid=").replace("&scan_type=player", "");
                  break;
               }
            }
         }
      }
   }
}

function setJumpPoint(){
   var html = document.getElementsByTagName("head")[0].innerHTML;
   var location = 0;
   if(html.indexOf("userloc = ") != -1){
      location = html.substring(html.indexOf("userloc = ") + 10, html.indexOf(";", html.indexOf("userloc = ")));
      if(location != 0){
         localStorage.setItem(universe + "JP", location);
      }
   }
}

function exitInner(){
   document.location = "main.php?exitsb=1";
}

function jumpToTile(){
   if(localStorage.getItem(universe + "JP") != null){
      if (document.location.href.match("building.php")){
         //we're on a blocking building... find the Retreat button and click it:
         var btn = document.getElementsByName("retreat");
            if(btn[0]) {
               btn[0].click();
            }
      }
      var jumptileId  = localStorage.getItem(universe + "JP");
      document.getElementById('navForm').elements[0].value = jumptileId;
      document.getElementById('navForm').submit();
   }
}

///////////////////////////////////////////////////////////////
// BOT CONSUMPTION FUNCTIONS
// =========================
///////////////////////////////////////////////////////////////

function consumeBots(){
   var bots = getAvailableBots();
   if(bots > 0){
      var currentArmor = getCurrentArmorPoints();
      var maxArmor = myArmorInfo[universe].ap;
      var armorClass = myArmorInfo[universe].ac;
      if(currentArmor <= (maxArmor - armorClass)){
         var botNo = Math.floor((maxArmor - currentArmor) / armorClass);
         if(botNo > bots){
            botNo = bots;
         }
         if (document.location.href.match("combat.php")){
            document.getElementById("bot_am").value = botNo;
            document.getElementsByName("useres")[0].click();
         }
         else if (document.location.href.match("main.php")){
            var link = findUseBotLink(botNo);
            if(link){
               document.location = link;
            }
         }
      }
   }
}

function findUseBotLink(amount){
   for(var i = 0; i < document.links.length; i++){
      var a = document.links[i];
      if(a.getAttribute("href").indexOf("main.php?use=8") != -1){
         document.links[i].setAttribute("href", "main.php?amount=" +  amount + "&resid=8&useres=Use");
         return document.links[i];
      }
   }
   return null;
}

function getAvailableBots(){
   if (document.location.href.match("combat.php")){
      var botHTML = document.getElementsByTagName("table")[2].innerHTML;
      var botPos = botHTML.indexOf("alt=\"Robots\"");
      if(botPos != -1){
         //There are bots on board
         botPos += 37;
         var stopPos = botHTML.indexOf("<", botPos);
         return parseInt(botHTML.substring(botPos, stopPos));
      }   
   }
   else if (document.location.href.match("main.php")){
      var imgtag = document.getElementsByTagName('img');
      for(var i = 0; i < imgtag.length; i++){
         if(imgtag[i].getAttribute('alt') == 'Robots'){
            var nrbots = imgtag[i].parentNode.textContent.split(" ")[0].replace(':', '');
            return nrbots;
         }
      }
   }
   //No bots on board
   return 0;
}

function getCurrentArmorPoints(){
   if (document.location.href.match("combat.php")){
      var html = document.getElementsByTagName("table")[3].innerHTML;
      var armourPos = html.indexOf("Armor points:");
      if(armourPos != -1){
         armourPos += 14;
         var stopPos = html.indexOf("<", armourPos);
         return parseInt(html.substring(armourPos, stopPos));
      }
   }
   else if (document.location.href.match('main.php')){
      var armorTable = document.getElementsByName("cloaking")[0].parentNode.getElementsByTagName("table")[0];
      return armorTable.rows[1].getElementsByTagName("font")[1].textContent;
   }
   return 0;
}
// ==/UserScript==